<template>
  <div class="message-renderer">
    <span v-for="(part, index) in renderedParts" :key="index">
      <template v-if="part.type === 'text'">
        {{ part.content }}
      </template>
      <template v-else-if="part.type === 'image'">
        <div class="message-image">
          <img 
            v-if="part.url"
            :src="part.url" 
            :alt="part.name || ''"
            @click="previewImage(part.url)"
            class="image-preview"
          />
          <div v-else class="file-tag image-tag">
            <el-icon class="tag-icon"><Picture /></el-icon>
            <span class="tag-text">{{ part.name || '' }}</span>
          </div>
          <div v-if="part.url" class="image-info">
            <span class="image-name">{{ part.name || '' }}</span>
            <el-button type="text" size="small" @click="downloadFile(part.url, part.name || '')">
              <el-icon><Download /></el-icon>
            </el-button>
          </div>
        </div>
      </template>
      <template v-else-if="part.type === 'file'">
        <div class="message-file">
          <div v-if="part.url" class="file-info">
            <el-icon class="file-icon"><Document /></el-icon>
            <span class="file-name">{{ part.name || '' }}</span>
            <el-button type="text" size="small" @click="downloadFile(part.url, part.name || '')">
              <el-icon><Download /></el-icon>
            </el-button>
          </div>
          <div v-else class="file-tag document-tag">
            <el-icon class="tag-icon"><Document /></el-icon>
            <span class="tag-text">{{ part.name || '' }}</span>
          </div>
        </div>
      </template>
    </span>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, Document, Picture } from '@element-plus/icons-vue'

interface Props {
  content: string
}

const props = defineProps<Props>()

// 定义消息部分的类型
interface MessagePart {
  type: 'text' | 'image' | 'file'
  content?: string
  name?: string
  url?: string
}

// 解析消息内容，识别文件链接
const renderedParts = computed(() => {
  const parts: MessagePart[] = []
  
  let remaining = props.content
  let lastIndex = 0
  
  // 匹配图片链接格式: [图片: filename](url)
  const imageRegex = /\[图片:\s*([^\]]+)\]\(([^)]+)\)/g
  let match
  
  while ((match = imageRegex.exec(remaining)) !== null) {
    // 添加匹配前的文本
    if (match.index > lastIndex) {
      const textContent = remaining.substring(lastIndex, match.index)
      if (textContent.trim()) {
        parts.push({ type: 'text' as const, content: textContent })
      }
    }
    
    // 添加图片
    parts.push({
      type: 'image',
      name: match[1],
      url: match[2]
    })
    
    lastIndex = match.index + match[0].length
  }
  
  // 匹配文件链接格式: [文件: filename](url)
  const fileRegex = /\[文件:\s*([^\]]+)\]\(([^)]+)\)/g
  lastIndex = 0 // 重置索引
  
  while ((match = fileRegex.exec(remaining)) !== null) {
    // 添加匹配前的文本
    if (match.index > lastIndex) {
      const textContent = remaining.substring(lastIndex, match.index)
      if (textContent.trim()) {
        parts.push({ type: 'text' as const, content: textContent })
      }
    }
    
    // 添加文件
    parts.push({
      type: 'file',
      name: match[1],
      url: match[2]
    })
    
    lastIndex = match.index + match[0].length
  }
  
  // 添加剩余文本
  if (lastIndex < remaining.length) {
    const textContent = remaining.substring(lastIndex)
    if (textContent.trim()) {
      parts.push({ type: 'text', content: textContent })
    }
  }
  
  // 如果没有匹配到任何链接，检查是否有文件标签格式 [filename]
  if (parts.length === 0 || (parts.length === 1 && parts[0].type === 'text')) {
    const textContent = parts.length === 0 ? props.content : parts[0].content || ''
    
    // 匹配文件标签格式: [filename]
    const fileTagRegex = /\[([^\]]+)\]/g
    const newParts: MessagePart[] = []
    
    let textIndex = 0
    let tagMatch
    
    while ((tagMatch = fileTagRegex.exec(textContent)) !== null) {
      // 添加匹配前的文本
      if (tagMatch.index > textIndex) {
        const beforeText = textContent.substring(textIndex, tagMatch.index)
        if (beforeText.trim()) {
          newParts.push({ type: 'text' as const, content: beforeText })
        }
      }
      
      // 添加文件标签
      const fileName = tagMatch[1]
      const isImage = /\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i.test(fileName) || 
                     /\.(jpg|jpeg|png|gif|bmp|webp|svg)\.\.\.$/i.test(fileName)
      
      newParts.push({
        type: (isImage ? 'image' : 'file') as 'image' | 'file',
        name: fileName,
        url: '' // 标签格式没有URL
      })
      
      textIndex = tagMatch.index + tagMatch[0].length
    }
    
    // 添加剩余文本
    if (textIndex < textContent.length) {
      const remainingText = textContent.substring(textIndex)
      if (remainingText.trim()) {
        newParts.push({ type: 'text' as const, content: remainingText })
      }
    }
    
    return newParts.length > 0 ? newParts : [{ type: 'text' as const, content: props.content }]
  }
  
  return parts
})

// 预览图片
const previewImage = (url: string) => {
  // 这里可以集成图片预览组件
  window.open(url, '_blank')
}

// 下载文件
const downloadFile = async (url: string, filename: string) => {
  try {
    const response = await fetch(url)
    const blob = await response.blob()
    
    const downloadUrl = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(downloadUrl)
    
    ElMessage.success('文件下载开始')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('文件下载失败')
  }
}
</script>

<style scoped>
.message-renderer {
  word-wrap: break-word;
  line-height: 1.4;
}

.message-image {
  margin: 8px 0;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e5e7eb;
  background: #f9fafb;
}

.image-preview {
  width: 100%;
  max-width: 300px;
  height: auto;
  cursor: pointer;
  transition: transform 0.2s;
}

.image-preview:hover {
  transform: scale(1.02);
}

.image-info {
  padding: 8px 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  border-top: 1px solid #e5e7eb;
}

.image-name {
  font-size: 12px;
  color: #6b7280;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 8px;
}

.message-file {
  margin: 8px 0;
  padding: 12px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #f9fafb;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  color: #6b7280;
  font-size: 16px;
}

.file-name {
  flex: 1;
  font-size: 14px;
  color: #374151;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 暗色主题支持 */
.dark .message-image {
  border-color: #374151;
  background: #111827;
}

.dark .image-info {
  background: #1f2937;
  border-color: #374151;
}

.dark .image-name {
  color: #9ca3af;
}

.dark .message-file {
  border-color: #374151;
  background: #111827;
}

.dark .file-name {
  color: #f9fafb;
}

/* 文件标签样式 */
.file-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  margin: 2px;
  border: 1px solid;
}

.image-tag {
  background: #fef3c7;
  border-color: #f59e0b;
  color: #92400e;
}

.document-tag {
  background: #dbeafe;
  border-color: #3b82f6;
  color: #1e40af;
}

.tag-icon {
  font-size: 12px;
}

.tag-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 60px;
}

/* 暗色主题支持 */
.dark .image-tag {
  background: #451a03;
  border-color: #f59e0b;
  color: #fbbf24;
}

.dark .document-tag {
  background: #1e3a8a;
  border-color: #3b82f6;
  color: #93c5fd;
}
</style>
